package com.example.zelonghu.testsqllite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private Button button1 = null;
    SQLiteDatabase db = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                db= SQLiteDatabase.openOrCreateDatabase(getFilesDir().getPath()+"/sql.db",null);
                createTable(db);
                insert(db);
                query(db);
            }
        });
    }
    private void createTable(SQLiteDatabase db){
        try {
            //创建表SQL语句
            String stu_table = "create table sensingdatalist(id integer primary key autoincrement,time varchar[10],type integer,value1 real,value2 real,value3 real)";
            //执行SQL语句
            db.execSQL(stu_table);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private void insert(SQLiteDatabase db){
        //实例化常量值
        ContentValues cValue = new ContentValues();
        //添加数据
        cValue.put("time",System.currentTimeMillis()+"");
        cValue.put("type",0);
        cValue.put("value1",0.01);
        cValue.put("value2",0.02);
        cValue.put("value3",0.03);

        //调用insert()方法插入数据
        db.insert("sensingdatalist",null,cValue);
    }
    private void query(SQLiteDatabase db) {
        //查询获得游标
        Cursor cursor = db.query ("sensingdatalist",null,null,null,null,null,null);

        //判断游标是否为空
        if(cursor.moveToFirst()) {
            //遍历游标
            for(int i=0;i<cursor.getCount();i++){
                cursor.move(i);
                int id = cursor.getInt(0);
                String time=cursor.getString(1);
                //String password=cursor.getString(2);
                String type=cursor.getString(2);
                String value1=cursor.getString(3);
                String value2=cursor.getString(4);
                String value3=cursor.getString(5);
                Log.i("test",id+":"+time + type+value1+value2+value3);
            }
        }
    }
}
